﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using AcsCommon;
using System.Data;

namespace YiShiService.Class
{
    public static class DataExt
    {
        public static string[] GetProperties(Type type)
        {
            List<string> names = new List<string>();
            var props = type.GetProperties();
            foreach (var prop in props)
            {
                if (prop.PropertyType.IsValueType || prop.PropertyType.IsEnum
                    || prop.PropertyType.Equals(typeof(String)))
                {
                    names.Add(prop.Name);
                }
            }
            return names.ToArray();
        }


        public static void FillObject(this DataRecord rec, object obj)
        {
            var props = GetProperties(obj.GetType());
            foreach (DataItem item in rec.Items)
            {
                if (Array.IndexOf<string>(props, item.Name) >= 0)
                {
                    //if (string.IsNullOrEmpty(item.Value))
                    //    obj.SetPropertyValue(item.Name, null);
                    //else
                    obj.SetPropertyValue(item.Name, item.Value);
                }
            }
        }
        public static void SetData(this DataRecord rec, object obj)
        {
            var props = GetProperties(obj.GetType());
            foreach (DataItem item in rec.Items)
            {
                if (Array.IndexOf<string>(props, item.Name) >= 0)
                    rec[item.Name] = obj.GetPropertyValue(item.Name);
            }
        }

        public static void FillObject(this DataRow row, object obj)
        {
            var props = GetProperties(obj.GetType());
            foreach (DataColumn col in row.Table.Columns)
            {
                if (Array.IndexOf<string>(props, col.ColumnName) >= 0)
                {
                    obj.SetPropertyValue(col.ColumnName, row.GetValue(col.ColumnName));
                }
            }
        }
    }
}
